package com.example.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.entity.User;
import com.example.exception.CustomerException;
import com.example.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Resource
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.从请求头拿到token
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)){
            // 如果没拿到，从参数里再拿一次
            token = request.getParameter("token");
        }
        // 2.认证token
        if (StrUtil.isBlank(token)){
            throw new CustomerException("401","请重新登录");
        }
        User user = null;
        try {
            // 拿到token的载荷数据
            String audience = JWT.decode(token).getAudience().get(0);
            String[] split = audience.split("-");
            Integer userId = Integer.valueOf(split[0]);
            user = userService.selectById(userId);
        }catch (Exception e){
            throw new CustomerException("401","无权操作");
        }
        if (user == null){
            throw new CustomerException("401","用户不存在，请重新登录");
        }

        // 验证token
        try {
            JWTVerifier jwtVerifier =JWT.require(Algorithm.HMAC256(user.getPassword())).build();
            jwtVerifier.verify(token);
        }catch (Exception e){
            throw new CustomerException("401","无权操作");
        }

        return true;
    }
}
